#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import ttk, messagebox
import time
from datetime import datetime

class BattleWindow:
    def __init__(self, parent, game_manager):
        self.parent = parent
        self.game_manager = game_manager
        self.window = tk.Toplevel(parent)
        self.update_timer = None
        self.setup_window()
        self.create_widgets()
        self.start_update_loop()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title("战斗系统")
        self.window.geometry("800x700")
        self.window.resizable(True, True)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 50, self.parent.winfo_rooty() + 50))
        
        # 绑定关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.close_window)
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.window.columnconfigure(0, weight=1)
        self.window.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="战斗系统", font=('Arial', 14, 'bold'))
        title_label.grid(row=0, column=0, pady=(0, 10))
        
        # 当前状态框架
        self.create_status_frame(main_frame)
        
        # 创建选项卡
        self.create_notebook(main_frame)
        
        # 控制按钮框架
        self.create_control_frame(main_frame)
        
        # 关闭按钮
        ttk.Button(main_frame, text="关闭", command=self.close_window).grid(row=4, column=0, pady=(10, 0))
        
    def create_status_frame(self, parent):
        """创建状态显示框架"""
        status_frame = ttk.LabelFrame(parent, text="角色状态", padding="10")
        status_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        status_frame.columnconfigure(1, weight=1)
        
        # 角色信息
        current_char = self.game_manager.get_current_character()
        char_info = f"{current_char.name} (Lv.{current_char.level} {current_char.character_class})"
        ttk.Label(status_frame, text="当前角色:", font=('Arial', 10, 'bold')).grid(row=0, column=0, sticky=tk.W, pady=2)
        ttk.Label(status_frame, text=char_info).grid(row=0, column=1, sticky=tk.W, pady=2)
        
        # 战斗力
        battle_power = current_char.attack + current_char.defense + current_char.speed
        ttk.Label(status_frame, text="战斗力:", font=('Arial', 10, 'bold')).grid(row=1, column=0, sticky=tk.W, pady=2)
        ttk.Label(status_frame, text=str(battle_power)).grid(row=1, column=1, sticky=tk.W, pady=2)
        
        # 战斗状态
        ttk.Label(status_frame, text="战斗状态:", font=('Arial', 10, 'bold')).grid(row=2, column=0, sticky=tk.W, pady=2)
        self.battle_status_label = ttk.Label(status_frame, text="空闲")
        self.battle_status_label.grid(row=2, column=1, sticky=tk.W, pady=2)
        
    def create_notebook(self, parent):
        """创建选项卡"""
        self.notebook = ttk.Notebook(parent)
        self.notebook.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        
        # 可用战斗选项卡
        self.create_available_battles_tab()
        
        # 我的战斗选项卡
        self.create_my_battles_tab()
        
        # 战斗历史选项卡
        self.create_battle_history_tab()
        
    def create_available_battles_tab(self):
        """创建可用战斗选项卡"""
        tab_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(tab_frame, text="可用战斗")
        
        tab_frame.columnconfigure(0, weight=1)
        tab_frame.rowconfigure(0, weight=1)
        
        # 战斗列表
        columns = ('id', 'type', 'creator', 'teams', 'status')
        self.available_tree = ttk.Treeview(tab_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题
        self.available_tree.heading('id', text='战斗ID')
        self.available_tree.heading('type', text='类型')
        self.available_tree.heading('creator', text='创建者')
        self.available_tree.heading('teams', text='队伍情况')
        self.available_tree.heading('status', text='状态')
        
        # 设置列宽
        self.available_tree.column('id', width=100)
        self.available_tree.column('type', width=80)
        self.available_tree.column('creator', width=120)
        self.available_tree.column('teams', width=150)
        self.available_tree.column('status', width=80)
        
        # 添加滚动条
        scrollbar1 = ttk.Scrollbar(tab_frame, orient=tk.VERTICAL, command=self.available_tree.yview)
        self.available_tree.configure(yscrollcommand=scrollbar1.set)
        
        self.available_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar1.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 绑定双击事件
        self.available_tree.bind('<Double-1>', self.on_available_battle_double_click)
        
    def create_my_battles_tab(self):
        """创建我的战斗选项卡"""
        tab_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(tab_frame, text="我的战斗")
        
        tab_frame.columnconfigure(0, weight=1)
        tab_frame.rowconfigure(0, weight=1)
        
        # 战斗列表
        columns = ('id', 'type', 'my_team', 'enemy_team', 'status')
        self.my_battles_tree = ttk.Treeview(tab_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题
        self.my_battles_tree.heading('id', text='战斗ID')
        self.my_battles_tree.heading('type', text='类型')
        self.my_battles_tree.heading('my_team', text='我方队伍')
        self.my_battles_tree.heading('enemy_team', text='敌方队伍')
        self.my_battles_tree.heading('status', text='状态')
        
        # 设置列宽
        self.my_battles_tree.column('id', width=100)
        self.my_battles_tree.column('type', width=80)
        self.my_battles_tree.column('my_team', width=150)
        self.my_battles_tree.column('enemy_team', width=150)
        self.my_battles_tree.column('status', width=80)
        
        # 添加滚动条
        scrollbar2 = ttk.Scrollbar(tab_frame, orient=tk.VERTICAL, command=self.my_battles_tree.yview)
        self.my_battles_tree.configure(yscrollcommand=scrollbar2.set)
        
        self.my_battles_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar2.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 绑定双击事件
        self.my_battles_tree.bind('<Double-1>', self.on_my_battle_double_click)
        
    def create_battle_history_tab(self):
        """创建战斗历史选项卡"""
        tab_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(tab_frame, text="战斗历史")
        
        tab_frame.columnconfigure(0, weight=1)
        tab_frame.rowconfigure(0, weight=1)
        
        # 历史列表
        columns = ('id', 'type', 'result', 'winner', 'end_time')
        self.history_tree = ttk.Treeview(tab_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题
        self.history_tree.heading('id', text='战斗ID')
        self.history_tree.heading('type', text='类型')
        self.history_tree.heading('result', text='结果')
        self.history_tree.heading('winner', text='获胜方')
        self.history_tree.heading('end_time', text='结束时间')
        
        # 设置列宽
        self.history_tree.column('id', width=100)
        self.history_tree.column('type', width=80)
        self.history_tree.column('result', width=80)
        self.history_tree.column('winner', width=120)
        self.history_tree.column('end_time', width=150)
        
        # 添加滚动条
        scrollbar3 = ttk.Scrollbar(tab_frame, orient=tk.VERTICAL, command=self.history_tree.yview)
        self.history_tree.configure(yscrollcommand=scrollbar3.set)
        
        self.history_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar3.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 绑定双击事件
        self.history_tree.bind('<Double-1>', self.on_history_battle_double_click)
        
    def create_control_frame(self, parent):
        """创建控制按钮框架"""
        control_frame = ttk.Frame(parent)
        control_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 按钮
        ttk.Button(control_frame, text="创建战斗", command=self.create_battle).grid(row=0, column=0, padx=(0, 10))
        ttk.Button(control_frame, text="加入战斗", command=self.join_battle).grid(row=0, column=1, padx=(0, 10))
        ttk.Button(control_frame, text="离开战斗", command=self.leave_battle).grid(row=0, column=2, padx=(0, 10))
        ttk.Button(control_frame, text="开始战斗", command=self.start_battle).grid(row=0, column=3, padx=(0, 10))
        ttk.Button(control_frame, text="刷新列表", command=self.refresh_all_lists).grid(row=0, column=4)
        
    def get_selected_battle_id(self, tree):
        """获取选中的战斗ID"""
        selection = tree.selection()
        if not selection:
            return None
        item = selection[0]
        values = tree.item(item, 'values')
        return values[0] if values else None
        
    def create_battle(self):
        """创建战斗"""
        dialog = CreateBattleDialog(self.window, self.game_manager)
        if dialog.result:
            self.refresh_all_lists()
            messagebox.showinfo("成功", f"战斗 {dialog.result} 创建成功！")
            
    def join_battle(self):
        """加入战斗"""
        battle_id = self.get_selected_battle_id(self.available_tree)
        if not battle_id:
            messagebox.showwarning("警告", "请先选择一个可用的战斗！")
            return
            
        # 选择队伍
        team_choice = messagebox.askyesnocancel("选择队伍", "选择要加入的队伍：\n\n是 - 队伍1\n否 - 队伍2\n取消 - 取消操作")
        
        if team_choice is None:
            return
            
        team = 1 if team_choice else 2
        
        try:
            self.game_manager.join_battle(battle_id, team)
            messagebox.showinfo("成功", f"成功加入战斗 {battle_id} 的队伍{team}！")
            self.refresh_all_lists()
        except Exception as e:
            messagebox.showerror("错误", f"加入战斗失败: {str(e)}")
            
    def leave_battle(self):
        """离开战斗"""
        current_char = self.game_manager.get_current_character()
        
        if not current_char.is_in_battle:
            messagebox.showinfo("提示", "您当前没有参与任何战斗！")
            return
            
        if messagebox.askyesno("确认离开", f"确定要离开战斗 {current_char.battle_id} 吗？"):
            try:
                self.game_manager.leave_battle(current_char.battle_id)
                messagebox.showinfo("成功", "成功离开战斗！")
                self.refresh_all_lists()
            except Exception as e:
                messagebox.showerror("错误", f"离开战斗失败: {str(e)}")
                
    def start_battle(self):
        """开始战斗"""
        battle_id = self.get_selected_battle_id(self.my_battles_tree)
        if not battle_id:
            messagebox.showwarning("警告", "请先选择一个您参与的战斗！")
            return
            
        try:
            result = self.game_manager.start_battle(battle_id)
            
            # 显示战斗结果
            if result:
                winner_team = result.get('winner_team', 'unknown')
                battle_log = result.get('battle_log', [])
                
                result_text = f"战斗结束！\n\n获胜队伍: 队伍{winner_team}\n\n战斗过程:"
                for log_entry in battle_log[-5:]:  # 显示最后5条日志
                    result_text += f"\n• {log_entry}"
                    
                messagebox.showinfo("战斗结果", result_text)
                self.refresh_all_lists()
            else:
                messagebox.showerror("错误", "战斗开始失败！")
                
        except Exception as e:
            messagebox.showerror("错误", f"开始战斗失败: {str(e)}")
            
    def refresh_all_lists(self):
        """刷新所有列表"""
        self.refresh_available_battles()
        self.refresh_my_battles()
        self.refresh_battle_history()
        self.update_battle_status()
        
    def refresh_available_battles(self):
        """刷新可用战斗列表"""
        # 清空现有项目
        for item in self.available_tree.get_children():
            self.available_tree.delete(item)
            
        # 获取可用战斗
        battles = self.game_manager.get_available_battles()
        
        for battle in battles:
            team1_count = len(battle.get('team1', []))
            team2_count = len(battle.get('team2', []))
            teams_info = f"{team1_count}v{team2_count}"
            
            creator_name = "未知"
            if battle.get('team1'):
                creator_name = battle['team1'][0].get('name', '未知')
            elif battle.get('team2'):
                creator_name = battle['team2'][0].get('name', '未知')
                
            self.available_tree.insert('', 'end', values=(
                battle['id'][:8],  # 显示前8位ID
                battle['type'],
                creator_name,
                teams_info,
                battle['status']
            ))
            
    def refresh_my_battles(self):
        """刷新我的战斗列表"""
        # 清空现有项目
        for item in self.my_battles_tree.get_children():
            self.my_battles_tree.delete(item)
            
        current_char = self.game_manager.get_current_character()
        if not current_char.is_in_battle:
            return
            
        # 获取当前角色参与的战斗
        battle = self.game_manager.get_battle(current_char.battle_id)
        if battle:
            # 确定我方和敌方队伍
            my_team = None
            enemy_team = None
            
            for char in battle.get('team1', []):
                if char['id'] == current_char.id:
                    my_team = battle['team1']
                    enemy_team = battle['team2']
                    break
                    
            if not my_team:
                for char in battle.get('team2', []):
                    if char['id'] == current_char.id:
                        my_team = battle['team2']
                        enemy_team = battle['team1']
                        break
                        
            if my_team is not None:
                my_team_names = [char['name'] for char in my_team]
                enemy_team_names = [char['name'] for char in enemy_team]
                
                self.my_battles_tree.insert('', 'end', values=(
                    battle['id'][:8],
                    battle['type'],
                    ', '.join(my_team_names),
                    ', '.join(enemy_team_names),
                    battle['status']
                ))
                
    def refresh_battle_history(self):
        """刷新战斗历史列表"""
        # 清空现有项目
        for item in self.history_tree.get_children():
            self.history_tree.delete(item)
            
        # 获取战斗历史
        history = self.game_manager.get_battle_history()
        
        for battle in history:
            # 确定结果
            current_char = self.game_manager.get_current_character()
            result = "未知"
            
            if battle.get('winner_team'):
                # 检查当前角色是否在获胜队伍中
                winner_team_key = f"team{battle['winner_team']}"
                winner_chars = battle.get(winner_team_key, [])
                
                for char in winner_chars:
                    if char['id'] == current_char.id:
                        result = "胜利"
                        break
                else:
                    # 检查是否在失败队伍中
                    loser_team_key = f"team{3 - battle['winner_team']}"
                    loser_chars = battle.get(loser_team_key, [])
                    for char in loser_chars:
                        if char['id'] == current_char.id:
                            result = "失败"
                            break
                            
            winner_info = f"队伍{battle.get('winner_team', '?')}" if battle.get('winner_team') else "无"
            end_time = datetime.fromtimestamp(battle.get('end_time', 0)).strftime("%m-%d %H:%M")
            
            self.history_tree.insert('', 'end', values=(
                battle['id'][:8],
                battle['type'],
                result,
                winner_info,
                end_time
            ))
            
    def update_battle_status(self):
        """更新战斗状态显示"""
        current_char = self.game_manager.get_current_character()
        
        if current_char.is_in_battle:
            self.battle_status_label.config(text=f"战斗中 ({current_char.battle_id[:8]})", foreground='red')
        else:
            self.battle_status_label.config(text="空闲", foreground='green')
            
    def on_available_battle_double_click(self, event):
        """双击可用战斗时加入"""
        self.join_battle()
        
    def on_my_battle_double_click(self, event):
        """双击我的战斗时开始战斗"""
        self.start_battle()
        
    def on_history_battle_double_click(self, event):
        """双击历史战斗时显示详情"""
        battle_id = self.get_selected_battle_id(self.history_tree)
        if battle_id:
            self.show_battle_details(battle_id)
            
    def show_battle_details(self, battle_id):
        """显示战斗详情"""
        # 这里可以实现战斗详情对话框
        messagebox.showinfo("战斗详情", f"战斗ID: {battle_id}\n\n详细信息功能待实现...")
        
    def start_update_loop(self):
        """启动更新循环"""
        def update_loop():
            self.update_battle_status()
            self.update_timer = self.window.after(5000, update_loop)  # 每5秒更新一次
            
        update_loop()
        
    def close_window(self):
        """关闭窗口"""
        if self.update_timer:
            self.window.after_cancel(self.update_timer)
        self.window.destroy()

class CreateBattleDialog:
    def __init__(self, parent, game_manager):
        self.parent = parent
        self.game_manager = game_manager
        self.result = None
        self.window = tk.Toplevel(parent)
        self.setup_window()
        self.create_widgets()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title("创建战斗")
        self.window.geometry("350x200")
        self.window.resizable(False, False)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 150, self.parent.winfo_rooty() + 150))
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        ttk.Label(main_frame, text="创建新战斗", font=('Arial', 14, 'bold')).grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 战斗类型选择
        ttk.Label(main_frame, text="战斗类型:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.type_var = tk.StringVar()
        type_combo = ttk.Combobox(main_frame, textvariable=self.type_var, state="readonly", width=15)
        type_combo['values'] = ('PVP', 'PVE', '公会战')
        type_combo.grid(row=1, column=1, sticky=(tk.W, tk.E), pady=5)
        type_combo.current(0)  # 默认选择PVP
        
        # 队伍选择
        ttk.Label(main_frame, text="加入队伍:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.team_var = tk.StringVar()
        team_combo = ttk.Combobox(main_frame, textvariable=self.team_var, state="readonly", width=15)
        team_combo['values'] = ('队伍1', '队伍2')
        team_combo.grid(row=2, column=1, sticky=(tk.W, tk.E), pady=5)
        team_combo.current(0)  # 默认选择队伍1
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=(20, 0))
        
        ttk.Button(button_frame, text="创建", command=self.create_battle).grid(row=0, column=0, padx=(0, 10))
        ttk.Button(button_frame, text="取消", command=self.cancel).grid(row=0, column=1)
        
        # 配置网格权重
        main_frame.columnconfigure(1, weight=1)
        
    def create_battle(self):
        """创建战斗"""
        battle_type = self.type_var.get()
        team_choice = self.team_var.get()
        
        if not battle_type:
            messagebox.showwarning("警告", "请选择战斗类型！")
            return
            
        if not team_choice:
            messagebox.showwarning("警告", "请选择队伍！")
            return
            
        team = 1 if team_choice == '队伍1' else 2
        
        try:
            battle_id = self.game_manager.create_battle(battle_type, team)
            self.result = battle_id
            self.window.destroy()
        except Exception as e:
            messagebox.showerror("错误", f"创建战斗失败: {str(e)}")
            
    def cancel(self):
        """取消创建"""
        self.window.destroy()